package com.han.yrpc.core.runtime.socket;

import com.han.yrpc.core.runtime.YrpcClient;
import com.han.yrpc.core.registry.ServiceInfo;
import com.han.yrpc.core.runtime.YRequest;
import com.han.yrpc.core.runtime.YResponse;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;

public class SocketYrpcClient implements YrpcClient {

    @Override
    @SuppressWarnings("unchecked")
    public YResponse<Object> send(YRequest request) {
        ServiceInfo serviceInfo = request.getServiceInfo();

        try (Socket socket = new Socket()) {
            socket.connect(new InetSocketAddress(serviceInfo.getHost(), serviceInfo.getPort()));

            ObjectOutputStream outputStream = new ObjectOutputStream(socket.getOutputStream());
            ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());

            outputStream.writeObject(request);
            outputStream.flush();

            return (YResponse<Object>) inputStream.readObject();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }
}
